<?php

namespace cms\modules\v1\models\user;

use api\modules\v1\models\user\UserKyc;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use Yii;

/**
 * 用户实名审核
 * Class OperationLog
 * @package cms\modules\v1\models\system
 */
class UserReal extends \common\models\user\UserReal
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @param array $search
     * @return array
     */
    public function getList($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'create_time DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], "*", $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $id_card = Yii::$app->request->get('id_card','');
        $status = Yii::$app->request->get('status','');
        $loginName = Yii::$app->request->get('login_name','');
        $true_name = Yii::$app->request->get('true_name','');


        if ($true_name ) {
            $andWhere[] = ['like','true_name',$true_name];
        }
        if ($id_card) {
            $andWhere[] = ['like','id_card',$id_card];
        }
        if ($status) {
            $where['status'] = (int) $status;
        }
        if ($loginName) {
            $ids = \common\models\user\User::searchByName($loginName);
            $where['user_id'] = $ids;
        }
        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }
        $list = $query->with([
            'user' => function ($q) {
                $q -> select(['id','login_name','nick_name']);
            },
        ])->asArray()->all();

        foreach ($list as &$v) {
            $v['status_name'] = STATUS::WITHDRAW_COIN_MAP[$v['status']];
            $v['user_face']= '';
            $v['oss_url']= static::getImages($v['oss_url']);
            $v['up_card_photo']= static::getImages($v['up_card_photo']);
            $v['back_card_photo']= static::getImages($v['back_card_photo']);
        }

        return $list;
    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('未知信息');
            }
            $info['image'] = [
                'url' => $info['image'] ? $this->getImages($info['image']) : '',
                'path' => $info['image']  ?: '',
            ];

            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $post = Yii::$app->request->post();
            $id = isset($post['id']) ? $post['id'] : 0;
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));
            if (!empty($id)) {
                //更新操作

                $res = static::updateData($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }
            } else {
                //添加操作
                $data['create_time'] = date('Y-m-d H:i:s');

                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }
            }
            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 添加修改
     * @return array
     */
    public function cancel() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $post = Yii::$app->request->post();
            $id = isset($post['id']) ? $post['id'] : 0;

            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $post = Yii::$app->request->post();
            $clean = (bool) $post['clean'];

            if (is_array($id)) {
                foreach ($id as $v) {
                    $this->doCancel($v);
                }
            } else {
                $this->doCancel($id);
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function doCancel ($id = 0, $clean = true){
        $info = static::getOneInfoById($id);
        $userInfo = User::getOneInfoById($info['user_id']);

        if ($info['is_kyc'] == Status::COMMON_RADIO_NO) {
            return true;
        }

        // 撤销实名后，用户为未实名状态，未实名状态，当前用户竞拍槌会清理掉，经验值、竞拍点、名誉值、活跃度清零，级别重置为LV0
        # 降级 改成 未实名
        $up['level_id'] = 1;
        $up['is_kyc'] = Status::COMMON_RADIO_NO;
        User::updateData($up, ['id' => $info['user_id']]);

        # delete 删除实名记录
        static::deleteAll(['id' => $id]);

    }

    /**
     * 审核
     * @return array
     * @throws \yii\db\Exception
     */
    public function doKyc() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $phone = Yii::$app->request->post('phone','');
            $name = Yii::$app->request->post('name','');
            $id_card = Yii::$app->request->post('id_card','');

            CacheKeys::checkFrequency("_KYC_{$phone}", 1);

            if (empty($phone)){
                throw new Exception('参数错误');
            }
            if (empty($name)){
                throw new Exception('参数错误');
            }
            if (empty($id_card)){
                throw new Exception('参数错误');
            }

            $userInfo = User::getOneByWhere(['login_name' => $phone]);

            if(empty($userInfo)) {
                throw new Exception('未知用户');
            }

            if($userInfo['is_kyc'] == Status::COMMON_RADIO_YES) {
                throw new Exception('该用户已经实名');
            }

            $kyc_num = static::getOneByWhere(['user_id'=>$userInfo['id']]);

            if($kyc_num){
                //有数据   修改
                throw new Exception('该用户已经实名');
//                $update_data['id_card'] = $id_card;
//                $update_data['true_name'] = $name;
//                $update_data['status'] = Status::COMMON_CHECKING_SUCCESS;
//                $res = static::updateData($update_data, ['user_id' => $userInfo['id']]);

            }else{
                //没有添加
                $date['id_card'] = $id_card;
                $date['true_name'] = $name;
                $date['user_id'] = $userInfo['id'];
                $date['create_time'] = date('Y-m-d H:i:s');
                $date['status'] = Status::COMMON_CHECKING_SUCCESS;
                $date['is_oss'] = Status::COMMON_RADIO_NO;
                $res = static::insertData($date);
                if($res == false){
                    throw new Exception('信息修改失败');
                }

            }


            $this->afterKYC($userInfo['id'], $userInfo['parent_id']);

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


}
